package io.renren.modules.admin.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import io.renren.common.utils.ShiroUtils;
import io.renren.modules.admin.entity.*;
import io.renren.modules.admin.entity.vo.DevHttpJsonVo;
import io.renren.modules.admin.entity.vo.ManagerTaskReqVo;
import io.renren.modules.admin.entity.vo.SendTaskVo;
import io.renren.modules.admin.service.ManagerContentService;
import io.renren.modules.admin.service.WarmContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import io.renren.modules.admin.entity.ManagerWorkEntity;
import io.renren.modules.admin.service.ManagerWorkService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.springframework.web.client.RestTemplate;


/**
 *
 * @author fangzq
 * @email canglx1996@163.com
 * @date 2020-12-11 10:54:23
 */
@RestController
@RequestMapping("admin/managerwork")
public class ManagerWorkController {
    @Autowired
    private ManagerWorkService managerWorkService;
    @Autowired
    private ManagerContentService managerContentService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private WarmContentService warmContentService;

    @GetMapping("api/getContext")
    public R getContext(String desc,Long userId) {
        ManagerContentEntity managerContentEntity = this.managerContentService.queryByDesc(desc,"1002",userId);
        if (managerContentEntity == null) {
            return R.error("没有对应评论");
        }
        String content = managerContentEntity.getContent();
        String[] split = content.split("\\|");
        String jsonString = JSON.toJSONString(split);
        return R.ok().put("context", jsonString);
    }

    /**
     * 用于发送多个任务
     */
    @PostMapping("api/taskLists")
    public R list2(@RequestBody ManagerWorkEntity managerWorkEntity) {
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登陆信息出错，请重新登陆");
        }
        String phoneIds = managerWorkEntity.getPhoneIds();
        String replace = phoneIds.trim().replace("|", ",");

        ManagerTaskReqVo taskReqVo = new ManagerTaskReqVo();
//        taskReqVo.setUrl(managerWorkEntity.getLiveAddr());
        taskReqVo.setUrl(managerWorkEntity.getLiveAddr().replace("#在抖音，记录美好生活#","").replace("正在直播，来和我一起支持TA吧","")
                .replace("复制下方链接，打开【抖音】，直接观看直播",""));
        taskReqVo.setApiPinBiUrl("http://47.107.104.4:8080/renren-fast/admin/warmup/api/getContext?desc="+managerWorkEntity.getShieldType()+"&userId="+userId);
        taskReqVo.setApiReplyUrl("http://47.107.104.4:8080/renren-fast/admin/managerwork/api/getContext?desc="+managerWorkEntity.getCommentType()+"&userId="+userId);
        taskReqVo.setCommentType(managerWorkEntity.getCommentType());
        taskReqVo.setCommentDelayStart(managerWorkEntity.getCommentDelayStart());
        taskReqVo.setCommentDelayEnd(managerWorkEntity.getCommentDelayEnd());
        taskReqVo.setCommentSendStart(managerWorkEntity.getCommentSendStart());
        taskReqVo.setCommentSendEnd(managerWorkEntity.getCommentSendEnd());
        taskReqVo.setAtRate(100);
        taskReqVo.setTaskName(managerWorkEntity.getWorkName());

        SendTaskVo map1 = new SendTaskVo(ManagerWorkEntity.OPTTYPE,taskReqVo);

        String jsonString = JSON.toJSONString(map1);

        String url = "http://dou.shciyun.com/open/common/send/tasks";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpMethod method = HttpMethod.POST;
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();

        // 封装数据
        map.add("data", jsonString);
//            map.add("deviceId", managerWorkEntity.getPhoneId().toString());
//            map.add("deviceId",freePhoneNumList.get(i));
        map.add("deviceIds",replace);
        map.add("type", "2");

        map.add("userId", String.valueOf(userId));

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        ResponseEntity<DevHttpJsonVo> response = this.restTemplate.exchange( url,method, request , DevHttpJsonVo.class );

        // 发送任务之后，保存任务到数据库
//            managerWorkEntity.setPhoneId(Long.parseLong(freePhoneNumList.get(i)));
        managerWorkEntity.setUserId(userId);

        managerWorkEntity.setLiveAddr(taskReqVo.getUrl());
        managerWorkEntity.setPhoneIds(replace);
        managerWorkEntity.setCreateTime(new Date());
        managerWorkService.save(managerWorkEntity);

        if (response.getBody().getCode() == 200) {
            return R.ok();
        }else {
            return R.error(response.getBody().getMsg());
        }
    }
    
    

    /**
     * 用于接收任务
     */
//    @PostMapping("api/taskList")
//    public R list(@RequestBody ManagerWorkEntity managerWorkEntity){
//        //commentType 不需要转
//        Long userId = ShiroUtils.getUserId();
//        if (userId == null) {
//            return R.error("登录信息出错，请重新登录");
//        }
//        ManagerTaskReqVo taskReqVo = new ManagerTaskReqVo();
//        taskReqVo.setUrl(managerWorkEntity.getLiveAddr().replace("#在抖音，记录美好生活#","").replace("正在直播，来和我一起支持TA吧","")
//                .replace("复制下方链接，打开【抖音】，直接观看直播",""));
//        taskReqVo.setApiPinBiUrl("http://47.107.104.4:8080/renren-fast/admin/warmup/api/getContext?desc="+managerWorkEntity.getShieldType()+"&userId="+userId);
//        taskReqVo.setApiReplyUrl("http://47.107.104.4:8080/renren-fast/admin/managerwork/api/getContext?desc="+managerWorkEntity.getCommentType()+"&userId="+userId);
//        taskReqVo.setCommentType(managerWorkEntity.getCommentType());
//        taskReqVo.setCommentDelayStart(managerWorkEntity.getCommentDelayStart());
//        taskReqVo.setCommentDelayEnd(managerWorkEntity.getCommentDelayEnd());
//        taskReqVo.setCommentSendStart(managerWorkEntity.getCommentSendStart());
//        taskReqVo.setCommentSendEnd(managerWorkEntity.getCommentSendEnd());
//        taskReqVo.setAtRate(100);
//
//        SendTaskVo map1 = new SendTaskVo(ManagerWorkEntity.OPTTYPE,taskReqVo);
//
////        MultiValueMap<String, Object> map1= new LinkedMultiValueMap<>();
////        map1.add("optType",ManagerWorkEntity.OPTTYPE);
////        map1.add("params",taskReqVo);
//        String jsonString = JSON.toJSONString(map1);
//
//        String url = "http://dou.shciyun.com/open/common/send/task";
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//        HttpMethod method = HttpMethod.POST;
//        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
//
//        // 封装数据
//        map.add("data", jsonString);
//        map.add("deviceId", managerWorkEntity.getPhoneIds());
//        map.add("type", "3");
//        map.add("userId", String.valueOf(userId));
//
//        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
//        ResponseEntity<DevHttpJsonVo> response = this.restTemplate.exchange( url,method, request , DevHttpJsonVo.class );
//
//        // 发送任务之后，设置当前时间，保存任务到数据库
//        managerWorkEntity.setCreateTime(new Date());
//        managerWorkEntity.setUserId(userId);
//        managerWorkService.save(managerWorkEntity);
//
//        return R.ok();
//    }

    /**
     * 查询所有暖场内容的评论描述
     */
    @RequestMapping("/commentType/manager/list")
    public R queryDesc(){
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登录信息出错，请重新登录");
        }
        List<String> descs = this.managerContentService.queryDesc(userId);
        return R.ok().put("list", descs);
    }
    @RequestMapping("/commentType/warm/list")
    public R queryWarmDesc(){
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登录信息出错，请重新登录");
        }
        List<String> descs = this.warmContentService.queryDesc(userId);
        return R.ok().put("list", descs);
    }
    
    
    
    
    
    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登录信息出错，请重新登录");
        }
        PageUtils page = managerWorkService.queryPage(params,userId);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		ManagerWorkEntity managerWork = managerWorkService.getById(id);

        return R.ok().put("managerWork", managerWork);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody ManagerWorkEntity managerWork){
//        managerWork.setCreateTime(new Date());
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登录信息出错，请重新登录");
        }
        managerWork.setUserId(userId);
		managerWorkService.save(managerWork);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody ManagerWorkEntity managerWork){
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登录信息出错，请重新登录");
        }
        managerWork.setUserId(userId);
		managerWorkService.updateById(managerWork);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		managerWorkService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
